import { throttle, isDefined, isFunction } from '@vimi/utils-tool'

const scope = 'selectLoadMore'
const handleScroll = function (cb) {
  const { el, container, vm } = this[scope]
  const disabledAttr = el.getAttribute('select-loadmore-disabled')
  const disabled = isDefined(disabledAttr)
    ? disabledAttr === 'false'
      ? false
      : Boolean(disabledAttr)
    : false
  if (disabled) return

  const distanceAttr = Number.parseInt(el.getAttribute('select-loadmore-distance'))
  const distance = Number.isNaN(distanceAttr) ? 0 : distanceAttr

  const { scrollHeight, scrollTop, clientHeight } = container
  if (scrollHeight - scrollTop - clientHeight <= distance) {
    cb.call(vm)
  }
}

export default {
  inserted(el, binding, vnode) {
    const cb = binding.value
    if (!isFunction(cb)) return

    const container = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
    if (!container) return

    const onScroll = throttle(200, handleScroll.bind(el, cb))

    const vm = vnode.context
    el[scope] = { el, vm, container, onScroll }

    container.addEventListener('scroll', onScroll)
  },
  unbind(el) {
    const { container, onScroll } = el[scope]
    if (container) {
      container.removeEventListener('scroll', onScroll)
    }
  },
}
